package controllers

import (
	"math/rand"
	"onion/utils/hand"
	"onion/utils/tool"
	"time"

	"github.com/astaxie/beego"
	"github.com/dgrijalva/jwt-go"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

type BaseController struct {
	beego.Controller
}

type JsonString struct {
	Code    int
	Message string
	Time    int
	Data    interface{}
}

// 成功返回
func (c *BaseController) Success(msg string, data ...interface{}) {
	j := JsonString{
		Code:    tool.SUCCESS,
		Message: msg,
		Time:    c.GetTime(),
		Data:    data,
	}
	c.Data["json"] = j
	c.ServeJSON()
}

// 失败返回
func (c *BaseController) ErrorJson(code int, msg string, data ...interface{}) {
	j := JsonString{
		Code:    code,
		Message: msg,
		Time:    c.GetTime(),
		Data:    data,
	}
	c.Data["json"] = j
	c.ServeJSON()
}

// 获取IP
func (c *BaseController) GetIP() string {
	return c.Ctx.Input.IP()
}

// 获取随机个数字符串
func (c *BaseController) RndStr(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	var result []byte
	for i := 0; i < l; i++ {
		result = append(result, bytes[rand.Intn(len(bytes))])
	}
	return string(result)
}

// 获取时间格式字符串
func (c *BaseController) GetTimeString() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

// 获取时间戳
func (c *BaseController) GetTime() int {
	return int(time.Now().Unix())
}

// 时间戳转年月日 时分秒
func (c *BaseController) DateFormat(timestamp int) string {
	tm := time.Unix(int64(timestamp), 0)
	return tm.Format("2006-01-02 15:04")
}

// 生成Token
func (c *BaseController) CreateToken() string {
	j := hand.NewJWT()
	id, _ := c.GetInt("id")
	claims := hand.CustomClaims{
		Id:   id,
		SKey: c.GetString("skey"),
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 1000, // 签名生效时间
			ExpiresAt: time.Now().Unix() + 3600, // 签名过期时间
			Issuer:    "king.top",
		},
	}
	token, err := j.CreateToken(claims)

	if err != nil {
		c.ErrorJson(-10, err.Error())
	}
	return token
}

// 验证Token
func (c *BaseController) ParserToken(token string) *hand.CustomClaims {
	j := hand.NewJWT()
	claims, err := j.ParserToken(token)
	if err != nil {
		c.ErrorJson(-10, err.Error())
	}
	return claims
}
